package com.bl.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;

import com.alibaba.fastjson.JSONObject;

public class ImageUtil {
	public static String identifyImage(InputStream inputStream) throws Exception {
		
		String result = "";
		
		Map< String, String> data = new HashMap<>();
        data.put("username","nickboowen100");
        data.put("password", "nickboowen");
        data.put("softid", "8f12c54d60464e60956938829b486a5c");
        data.put("typeid", "4");
        data.put("modelid", "");

        String resultString = Jsoup.connect("http://api.ttshitu.com/create.json")
                .data(data).data("image","test.jpg",inputStream)
                .ignoreContentType(true)
                .post().text();
        Map map = JSONObject.parseObject(resultString);
        if ((Boolean) map.get("success")) {
            Map map1 = JSONObject.parseObject(String.valueOf(map.get("data")));
            result=(String) map1.get("result");
            System.out.println("identify result :"+result);
        }else {
            System.out.println("identify result :"+map.get("message"));
        }
        return result;
	}
	public static boolean generateImage(final String imgStr, final String outPutFilePath) throws IOException {
        if (imgStr == null) {
            return false;
        }
        OutputStream out = null;
        try {
            final Base64.Decoder decoder = Base64.getDecoder();
            byte[] b = decoder.decode(imgStr);
            out = new FileOutputStream(outPutFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (IOException e) {
            throw e;
        } finally {
            if(out != null) {
                out.close();
            }
        }
    }

}
